<template>
    <div class="list">
        <Title>购物车</Title>
        <div class="table">
            <el-table ref="multipleTableRef" :data="borrow.list" style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="图片" width="120">
                    <template #default="scope">
                        <img :src="baseURL + scope.row.pic" alt="商品" style="width:80%">
                    </template>
                </el-table-column>
                <el-table-column prop="title" label="标题">
                    <template #default="scope">
                        <span style="cursor: pointer" @click="toDetail(scope.row.book_id)">{{ scope.row.title }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="price" label="价格" width="120">
                    <template #default="scope">
                        <span style="color:#409eff">
                            {{ '￥' + formatPrice(scope.row.price) }}
                        </span> 
                    </template>
                </el-table-column>
                <el-table-column prop="day" label="数量" width="150">
                    <template #default="scope">
                        <!-- 左右加减符号输入框 -->
                        <el-input-number v-model="scope.row.day"
                            style="width: 100px; margin-right: 10px;"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="buyGood(scope.row)">
                            购买
                        </el-button>
                        <el-button link type="danger" size="small" @click="deleteRow(scope.row.id)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="down">
            <div>合计:
                <span style="color: #409eff">￥{{ formatPrice(borrow.total) }}</span>
            </div>
            <el-button type="primary" @click="dialogVisible = true">结算</el-button>
        </div>
    </div>
    <!-- 提示对话框 -->
    <el-dialog v-model="dialogVisible" title="提示">
        <template #header>
            <div>
                你确定要购买以下商品吗？
            </div>
        </template>
        <div>
            <el-table :data="selection.list" border>
                <el-table-column label="图片">
                    <template #default="scope">
                        <img width="120px" height="120px" :src="baseURL + scope.row.pic" alt="商品">
                    </template>
                </el-table-column>
                <el-table-column prop="title" label="商品"></el-table-column>
                <el-table-column prop="price" label="价格" width="120">
                    <template #default="scope">
                        <span style="color:#409eff">{{ '￥' + formatPrice(scope.row.price) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="day" label="件数" width="150"></el-table-column>
            </el-table>
            <div style="margin-top:30px; font-size:16px; line-height: 25px;">
                <div>收件人：{{user.nickname}}</div>
                <div>手机号：{{user.phone}}</div>
                <div>收货地址：{{user.address}}</div>
                <div style="margin-top:40px;">合计：
                    <span style="color:#409eff;">￥{{borrow.total}}</span>
                </div>
            </div>
        </div>
        <!-- 确定按钮 -->
        <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleConfirm">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import Title from '@/components/Title.vue'
import { formatPrice } from '@/utils/formatPrice'
import { useRouter } from 'vue-router'
import { list, deleteBorrow, confirmBorrow } from '@/api/borrow'
import { userinfo } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/useUser'
import { baseURL } from '@/config/baseURL'

const userStore = useUserStore()

const router = useRouter()

const borrow = reactive({
    list: [],
    total: 0,
})

const dialogVisible = ref(false)

const multipleTableRef = ref(null)

const deleteRow = (id) => {
    ElMessageBox.confirm(
        '确定要删除吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        deleteBorrow({
            id
        }).then(res => {
            if (res.data.code === 200) {
                ElMessage.success('删除成功')
                borrow.list = borrow.list.filter(item => item.id !== id)
            } else {
                ElMessage.error(res.data.message)
            }
        })
    })

}

const selection = reactive({
    list: []
})

//多选回调
const handleSelectionChange = (val) => {

    selection.list = val;

    let total = 0;
    val.forEach(item => {
        total += +item.price * +item.day
    });

    if (total > 0) {
        borrow.total = total;
    } else {
        borrow.total = 0;
    }

}

const user = ref({})

//获取用户信息
const getUserinfo = () => {
    userinfo({id: userStore.userinfo.id}).then(res => {
        if (res.data.code == 200) {
            user.value = {...res.data.user}
        }
    })
}

getUserinfo()

//确定购买
const handleConfirm = () => {
    if(selection.list.length === 0){
        ElMessage.warning('未勾选任何商品')
        return
    }
    confirmBorrow({ list: selection.list }).then(res => {
        if (res.data.code === 200) {
            ElMessage.success(res.data.message);
            getList();
            dialogVisible.value = false
        } else {
            ElMessage.error(res.data.message);
        }
    })
}

//购买
const buyGood = (row) => {
    console.log(row);
    multipleTableRef.value.toggleRowSelection(row, undefined)
    dialogVisible.value = true;
}

//获取购物车列表
const getList = () => {
    list({
        user_id: userStore.userinfo.id
    }).then(res => {
        if (res.data.code == 200) {
            borrow.list = res.data.books
        }
        else {
            ElMessage.error(res.data.message)
        }
    })
}

getList()

//跳转详情页
const toDetail = (id) => {
    router.push('/detail/' + id)
}

//监听勾选数据变化
watch(() => selection.list, () => {

})

</script>

<style scoped lang='less'>
.list {
    height: 100%;

    .table {
        margin-top: 20px;
        height: 530px;
        overflow-y: auto;
    }

    .down {
        margin-top: 20px;
        color: #777;
        display: flex;
        justify-content: space-between;

        span {
            font-weight: bold;
        }
    }
}
</style>